//
//  GroupViewController.m
//  QRMaster
//
//  Created by myApple on 15/10/12.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "GroupViewController.h"
#import "addGroupViewController.h"
#import "MJRefresh.h"
#import "groupModel.h"
#import "GroupTableViewCell.h"
#import "groupGuestViewController.h"
#import "UIView+MaterialDesign.h"
#import "AppDelegate.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "ChineseString.h"
#import "pinyin.h"
#import "checkPower.h"
#import "ZYPinYinSearch.h"
#import "GroupLogic.h"
#import "BackBtn.h"

@interface GroupViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UIActionSheetDelegate,UISearchDisplayDelegate>
{
    
    UIView  * titleView;
    UIView * deleteView;
    NSMutableArray * allGroupArray;//总数据，便于搜索删除
    UITableView * groupTabelView;
    NSMutableArray * groupArray;
    UISearchBar * groupSearch;
    UISearchDisplayController * groupDisplayController;
    NSMutableArray * groupSearchData;
    NSMutableArray * deleteCellArray;//点击删除的cell
    UILabel * deleteCountLabel;//显示当前准备删除几个人
    UIView * noGroupView;
    
    UIButton * addBtn; //添加
    
    UILabel *titleLb; //nav上的title
    
    
    BOOL isFrist ; //是否是第一次请求
}

@end

@implementation GroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    isFrist = YES;
    groupArray = [[NSMutableArray alloc]init];
    allGroupArray = [[NSMutableArray alloc]init];
    groupSearchData = [[NSMutableArray alloc]init];
    deleteCellArray = [[NSMutableArray alloc]init];
    [self prepareTitleView];
    [self prepareTableView];
    [self noGroup];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!groupDisplayController.isActive) {
        [self getNewData];
    }
    if (YES == isFrist) {
        [self getGroupData];
        [self getNewData];
        isFrist = NO;
    }
    self.navigationController.navigationBarHidden = NO;
    addBtn.hidden = NO;
    titleLb.hidden = NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    titleLb.text = NSLocalizedString(@"groupManager", nil);
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    addBtn.hidden = YES;
    deleteView.hidden = YES;
    titleLb.hidden = YES;
}

-(void)getNewData
{
    __block NSMutableArray * listArray;
    GroupLogic *groupLogic =[[GroupLogic alloc]init];
    [groupLogic queryGroupInfo:[[NSUserDefaults standardUserDefaults] objectForKey:@"communityId"] block:^(NSMutableArray *arr) {
        listArray = arr;
    }];

    if(listArray.count != 0)
    {
        [allGroupArray removeAllObjects];
        noGroupView.hidden = YES;
    }
    allGroupArray = listArray;
    if (allGroupArray.count != 0)
    {
        groupArray = [allGroupArray mutableCopy];
        groupArray = [self getChinesArray:allGroupArray];
        
        for(int i = 0; i<groupArray.count; i++)
        {
            ((GroupModel*)[groupArray objectAtIndex:i]).groupHeaderWord=[self FirstCharToStr:((GroupModel *)[groupArray objectAtIndex:i]).groupHeaderWord];
        }
        //首字母处理
        for(int i = 0; i<groupArray.count; i++)
        {
            for(int j = i; j<groupArray.count; j++)
            {
                if([((GroupModel *)[groupArray objectAtIndex:i]).groupHeaderWord isEqualToString:((GroupModel *)[groupArray objectAtIndex:j]).groupHeaderWord]==YES &&j!=i)
                {
                    GroupModel * model = [[GroupModel alloc]init];
                    model=[groupArray objectAtIndex:j];
                    model.groupHeaderWord=@"";
                }
            }
        }
    }
    [groupTabelView reloadData];
}

-(void)prepareTitleView
{
    titleLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 44)];
    titleLb.backgroundColor = [UIColor clearColor];
    titleLb.textColor = [UIColor whiteColor];
    titleLb.text = NSLocalizedString(@"groupManager", nil);
    titleLb.textAlignment = NSTextAlignmentCenter;
    [self.navigationController.navigationBar addSubview:titleLb];
    
    
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = ScreenWidth - 40;
    float y = 0;
    float width = 40;
    float height = 40;

    addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(x, y, width, height);
    [addBtn addTarget:self action:@selector(addGroup) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:addBtn];
    
    UIImageView *addImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 30, 30)];
    UIImage * telePhoneImage = [UIImage imageNamed:@"ic_add30"];
    addImgView.image = telePhoneImage;
    [addBtn addSubview:addImgView];
    
    //删除状态下的导航栏
    x = 0;
    y = 0;
    width = ScreenWidth;
    height = 44;
    deleteView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    deleteView.backgroundColor = [UIColor blackColor];
    deleteView.userInteractionEnabled = YES;
    deleteView.hidden = YES;
    [self.navigationController.navigationBar addSubview:deleteView];
    
    //后退取消删除
    x = 0;
    y = 0;
    height = 40;
    width = 40;
    UIButton * clearDeleteBtn = [BackBtn initWithFrame:CGRectMake(x, y, width, height) withImage:@"24x24"];
    [clearDeleteBtn addTarget:self action:@selector(clearDelete) forControlEvents:UIControlEventTouchUpInside];
    [deleteView addSubview:clearDeleteBtn];
    
    x = 40;
    y = 10;
    height = 20;
    width = 120;
    deleteCountLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    deleteCountLabel.textColor = [UIColor whiteColor];
    deleteCountLabel.font = [UIFont systemFontOfSize:14.0];
    [deleteView addSubview:deleteCountLabel];
    
    //点击删除的按钮
    UIImageView * deleteImgView = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth - 40, 5, 30, 30)];
//    deleteImgView.image = [UIImage imageNamed:@"ic_36_gabage"];
    deleteImgView.userInteractionEnabled = YES;
    [deleteView addSubview:deleteImgView];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(deleteCell:)];
    [deleteImgView addGestureRecognizer:tap];
    
    UIImageView *iconView=[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 20, 20)];
    iconView.image=[UIImage imageNamed:@"ic_36_gabage"];
    [deleteImgView addSubview:iconView];
    deleteImgView.backgroundColor=[UIColor clearColor];
    
}

#pragma mark -- searchDelegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [groupArray removeAllObjects];
    groupArray = [NSMutableArray arrayWithArray:[ZYPinYinSearch searchWithOriginalArray:allGroupArray andSearchText:searchText andSearchByPropertyName:@"groupName"]];
    for (UIView * subView in groupDisplayController.searchResultsTableView.subviews)
    {
        if ([subView isKindOfClass:[UILabel class]]) {
            UILabel * label = (UILabel *)subView;
            label.text = NSLocalizedString(@"noSearch", nil);
        }
    }
    [groupTabelView reloadData];
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    //如果是从删除模式跳转到搜索模式则去掉删除模式
    [self clearDelete];
    //修改searchbar的“取消”变成多语言
    searchBar.showsCancelButton = YES;
    for(id cc in [searchBar.subviews[0] subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:NSLocalizedString(@"alterCancel", nil) forState:UIControlStateNormal];
        }
    }
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    for (UIView * subView in groupDisplayController.searchResultsTableView.subviews)
    {
        if ([subView isKindOfClass:[UILabel class]]) {
            UILabel * label = (UILabel *)subView;
            label.text = NSLocalizedString(@"noSearch", nil);
        }
    }
    return YES;
}

#pragma mark -- cancleSearchbar
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [groupSearchData removeAllObjects];
    groupArray = [allGroupArray mutableCopy];
    groupArray = [self getChinesArray:allGroupArray];
    for(int i = 0; i<groupArray.count; i++)
    {
        ((GroupModel*)[groupArray objectAtIndex:i]).groupHeaderWord=[self FirstCharToStr:((GroupModel *)[groupArray objectAtIndex:i]).groupHeaderWord];
    }
    //首字母处理
    for(int i = 0; i<groupArray.count; i++)
    {
        for(int j = i; j<groupArray.count; j++)
        {
            if([((GroupModel *)[groupArray objectAtIndex:i]).groupHeaderWord isEqualToString:((GroupModel *)[groupArray objectAtIndex:j]).groupHeaderWord]==YES &&j!=i)
            {
                GroupModel * model = [[GroupModel alloc]init];
                model=[groupArray objectAtIndex:j];
                model.groupHeaderWord=@"";
            }
        }
    }

    [groupTabelView reloadData];
    [self clearDelete];
}


-(void)addGroup
{
    addGroupViewController * agvc = [[addGroupViewController alloc]init];
    agvc.communityId = _communityId;
    [self.navigationController pushViewController:agvc animated:YES];
}


-(void)prepareTableView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = 44;
    
    //搜索条的
    groupSearch = [[UISearchBar alloc]initWithFrame:CGRectMake(x, y, width, height)];
    groupSearch.placeholder = NSLocalizedString(@"searchGroupName", nil);
    groupSearch.layer.masksToBounds = YES;
    groupSearch.keyboardType = UIKeyboardTypeNamePhonePad;
    groupSearch.delegate = self;
    groupDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:groupSearch contentsController:self];
    groupDisplayController.searchResultsDataSource = self;
    groupDisplayController.searchResultsDelegate = self;
    groupDisplayController.delegate = self;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    
    
    x = 0;
    y = 0;
    width = ScreenWidth;
    height = ScreenHeight - y;
    groupTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height-64) style:UITableViewStylePlain];
    groupTabelView.dataSource = self;
    groupTabelView.delegate = self;
    groupTabelView.tableFooterView = [[UIView alloc]init];

    [self.view addSubview:groupTabelView];
    [groupTabelView.mj_header beginRefreshing];
    groupTabelView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getGroupData];
    }];
     groupTabelView.tableHeaderView = groupSearch;
    //长按删除
    UILongPressGestureRecognizer * gestureLongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(gestureLongPress:)];
    gestureLongPress.minimumPressDuration = 1.0;
    [groupTabelView addGestureRecognizer:gestureLongPress];
    
    UILongPressGestureRecognizer * gesturePress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(gesturePress:)];
    gestureLongPress.minimumPressDuration = 1.0;
    [groupDisplayController.searchResultsTableView addGestureRecognizer:gesturePress];
}


//没有任何组的情况下
-(void)noGroup
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = self.view.frame.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight;
    noGroupView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    noGroupView.backgroundColor = [UIColor whiteColor];
    noGroupView.hidden = YES;
    [self.view addSubview:noGroupView];
    
    x = 20;
    y = noGroupView.frame.size.height / 2.0 - 20;
    width = ScreenWidth - 2 * x;
    height = 40;
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(x, y, width, height);
    [btn setTitle:NSLocalizedString(@"add", nil) forState:0];
    [btn setBackgroundColor:RGBA(135, 199, 66, 1)];
    [btn addTarget:self action:@selector(addGroup) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.cornerRadius = 5;
    btn.layer.masksToBounds = YES;
    [noGroupView addSubview:btn];
    
}

#pragma mark -- 取消删除状态
-(void)clearDelete
{
    [UIView animateWithDuration:0.5 animations:^{
        titleView.hidden = NO;
        deleteView.hidden = YES;
    } completion:^(BOOL finished) {
        [self clearDeleteStyle];
    }];
}

#pragma mark -- 取消删除时改变cell的状态
-(void)clearDeleteStyle
{
    for (NSIndexPath * cancelIndexPath in deleteCellArray) {
        UITableViewCell * cell = [groupTabelView cellForRowAtIndexPath:cancelIndexPath];
        cell.backgroundColor = [UIColor whiteColor];
    }
    [deleteCellArray removeAllObjects];
}

#pragma mark -- 准备删除
-(void)deleteCell:(UITapGestureRecognizer *)tap
{
    UIActionSheet * quitAcitonSheet = [[UIActionSheet alloc]initWithTitle:NSLocalizedString(@"deleteGroupManager", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"not", nil) destructiveButtonTitle:NSLocalizedString(@"yes", nil) otherButtonTitles:nil];
    [quitAcitonSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        deleteView.hidden = YES;
        [self clearDelete];
    }
    else
    {
        [self makeSureDelete];
       
    }
}

#pragma mark -- 确认删除
-(void)makeSureDelete
{
    NSArray * sortArray = nil;
    if (deleteCellArray.count == 1) {
        sortArray = [deleteCellArray copy];
    }
    //排序
    else
    {
        sortArray = [deleteCellArray sortedArrayUsingComparator:^NSComparisonResult(NSIndexPath *obj1, NSIndexPath *obj2) {
            if (obj1.row > obj2.row) {
                return NSOrderedAscending;
            }
            else
            {
                return NSOrderedDescending;
            }
            
        }];
    }
    NSMutableString * memberIdString = [[NSMutableString alloc]init];
    //从大到小删除
    for (int i = 0; i < sortArray.count ; i ++) {
        NSInteger row = [[sortArray objectAtIndex:i]row];
        GroupModel * model = groupArray[row];
        [memberIdString appendString:model.groupId];
        [memberIdString appendString:@","];
        [groupArray removeObjectAtIndex:row];//删除数据源
    }
    [groupTabelView reloadData];
    [groupDisplayController.searchResultsTableView reloadData];
    /*
     删除 guesttableview 和 deleteguestcell 的顺序颠倒就会崩掉
     */
    @try {
        NSRange range;
        range.location = memberIdString.length - 1;
        range.length = 1;
        [memberIdString deleteCharactersInRange:range];
    }
    @catch (NSException *exception) {
        return;
    }
    
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDicts = [[NSMutableDictionary alloc]init];
    [postDicts setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDicts setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDicts setValue:_communityId forKey:@"communityId"];
    [postDicts setValue: memberIdString forKey:@"groupIds"];

    if([self getTimestamp:_communityId timeKey:@"group_timestamp"] != nil)
    {
        [postDicts setValue:[self getTimestamp:_communityId timeKey:@"group_timestamp"] forKey:@"timestamp"];
    }
    else
    {
        [postDicts setValue:@"" forKey:@"timestamp"];
    }

    [self startWaiting:nil color:nil addToView:self.view];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(DELETEGROUP)  params:postDicts block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         if([downLoadData objectForKey:@"cache"] != nil)
         {
             if([@"1" isEqualToString:[NSString stringWithFormat:@"%@",[[downLoadData objectForKey:@"cache"] objectForKey:@"status"]]]==YES)
             {
                 [self getGroupData];
             }
             else
             {
                 [self updateTimestamp:_communityId timeKey:@"group_timestamp" timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
                 if ([downLoadData objectForKey:@"data"] != nil)
                 {
                     GroupLogic *groupLogic = [[GroupLogic alloc]init];
                     [groupLogic deleteGroupInfo:memberIdString withCommunityId:_communityId];
                     [self getNewData];
                     
                 }
             }
         }
         
         if (error) {
             [self clearDelete];
             deleteView.hidden = YES;
             [PromptInfoView showMessage:[error objectForKey:@"info"]];
             if ([[error objectForKey:@"status"]integerValue] == 500)
             {
                 [self getGroupData];//用户在别处被删除了
             }

         }
     }];
       [self clearDelete];
}

#pragma mark -- 获取组数据
-(void)getGroupData
{
    if ([self IsHaveNetwork]) {
        [groupTabelView.mj_header endRefreshing];
        return;
    }

    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDicts = [[NSMutableDictionary alloc]init];
    [postDicts setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDicts setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDicts setValue:_communityId forKey:@"communityId"];
    
    if([self getTimestamp:_communityId timeKey:@"group_timestamp"] != nil)
    {
        [postDicts setValue:[self getTimestamp:_communityId timeKey:@"group_timestamp"] forKey:@"timestamp"];
    }
    else
    {
        [postDicts setValue:@"" forKey:@"timestamp"];
    }
    [self startWaiting:nil color:nil addToView:self.view];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    __weak GroupViewController * weakSelf = self;
    [rnw initWithPath:POST(GROUPLIST) params:postDicts block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         if([downLoadData objectForKey:@"cache"] != nil)
         {
             [self updateTimestamp:_communityId timeKey:@"group_timestamp" timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
             if([@"1" isEqualToString:[NSString stringWithFormat:@"%@",[[downLoadData objectForKey:@"cache"] objectForKey:@"status"]]]==YES)
             {
                 if ([downLoadData objectForKey:@"data"] != nil)
                 {
                     [allGroupArray removeAllObjects];//如果有更新就去掉从本地读的

                     GroupLogic *groupLogic = [[GroupLogic alloc]init];
                     [groupLogic deleteGroupInfo:_communityId];
                     
                     NSMutableDictionary *data = [downLoadData objectForKey:@"data"];
                     NSArray * listArray = [data objectForKey:@"groupList"];
                     for (NSDictionary * dict in listArray) {
                         GroupModel * model = [[GroupModel alloc]init];
                         model.groupId = [dict objectForKey:@"groupId"];
                         model.groupName = [dict objectForKey:@"groupName"];
                         model.groupManagerName = [dict objectForKey:@"groupManagerName"];
                         model.groupManagerMobile = [dict objectForKey:@"groupManagerMobile"];
                         model.groupManagerEmail = [dict objectForKey:@"groupManagerEmail"];
                         model.groupManagerCertificate = [dict objectForKey:@"groupId"];
                         model.groupEndTime = [dict objectForKey:@"endtime"];
                         model.groupBeginTime = [dict objectForKey:@"starttime"];
                         [allGroupArray addObject:model];
                         
                         GroupLogic *groupLogic = [[GroupLogic alloc]init];
                         [groupLogic insertGroupData:model withCommuntiyId:_communityId groupClient_timestamp:nil];
                     }
                 }
                 if (allGroupArray.count == 0) {
                     noGroupView.hidden = NO;
                 }
                 else
                 {
                     noGroupView.hidden = YES;
                     groupArray = [allGroupArray mutableCopy];
                     groupArray = [weakSelf getChinesArray:allGroupArray];
                     
                     for(int i = 0; i<groupArray.count; i++)
                     {
                         ((GroupModel*)[groupArray objectAtIndex:i]).groupHeaderWord=[self FirstCharToStr:((GroupModel *)[groupArray objectAtIndex:i]).groupHeaderWord];
                     }
                     
                     //首字母处理
                     for(int i = 0; i<groupArray.count; i++)
                     {
                         for(int j = i; j<groupArray.count; j++)
                         {
                             if([((GroupModel *)[groupArray objectAtIndex:i]).groupHeaderWord isEqualToString:((GroupModel *)[groupArray objectAtIndex:j]).groupHeaderWord]==YES &&j!=i)
                             {
                                 GroupModel * model = [[GroupModel alloc]init];
                                 model=[groupArray objectAtIndex:j];
                                 model.groupHeaderWord=@"";
                             }
                         }
                     }
                 }
                 
             }
             if (groupArray.count == 0) {
                 noGroupView.hidden = NO;
             }
             else
             {
                 noGroupView.hidden = YES;
             }
         }
         else
         {
             [PromptInfoView showMessage:[error objectForKey:@"info"] superView:weakSelf.view];
         }
         
         [groupTabelView.mj_header endRefreshing];
         [groupTabelView reloadData];
     }
     ];
  

    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return groupArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * string = @"cell";
    
        GroupTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (!cell) {
            cell = [[GroupTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
        }
    cell.backgroundColor = [UIColor whiteColor];
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
    for (NSIndexPath * selectIndexPath in deleteCellArray) {
        if (selectIndexPath.row == indexPath.row && selectIndexPath.section == indexPath.section) {
            cell.backgroundColor = RGBA(255, 255, 255, 1);
            break;
        }
    }
        if (groupArray.count > indexPath.row) {
            GroupModel * model = groupArray[indexPath.row];
            cell.titleHead = model.groupHeaderWord;
            cell.groupId = model.groupId;
            cell.groupManagerAccount = model.groupManagerMobile;
            cell.groupName = model.groupName;
            cell.groupManagerName = model.groupManagerName;
            cell.groupManagerCertificate = model.groupManagerCertificate;
            cell.groupImage = @"groupHead";
        }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (deleteCellArray.count > 0) {
        for (NSIndexPath * deleteIndexPath in deleteCellArray) {
            if (indexPath.row == deleteIndexPath.row && indexPath.section == deleteIndexPath.section) {
                GroupTableViewCell * cell = (GroupTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
                [cell mdDeflateAnimatedToPoint:CGPointMake(cell.frame.size.width /2.0, cell.frame.size.height / 2.0) backgroundColor:[UIColor whiteColor] duration:0.5 completion:nil];
                [deleteCellArray removeObject:indexPath];
                [self showDeleteView];
                if (deleteCellArray.count == 0) {
                    [self clearDelete];
                }
                return;
            }
        }
        if (indexPath == nil) {
            return;
        }
        GroupTableViewCell * cell = (GroupTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell mdInflateAnimatedFromPoint:CGPointMake(cell.frame.size.width /2.0, cell.frame.size.height / 2.0)  backgroundColor: RGBA(225, 225, 225, 1) duration:0.5 completion:nil];
        [deleteCellArray addObject:indexPath];
        [self showDeleteView];
        return;
    }
    
   [QRSingleton sharedQRSingleton].groupPush = @"1";
    groupGuestViewController * ggvc = [[groupGuestViewController alloc]init];
    GroupModel * model = groupArray[indexPath.row];
    ggvc.groupId = model.groupId;
    ggvc.groupName = model.groupName;
    ggvc.communityId = _communityId;
    [QRSingleton sharedQRSingleton].groupBeginTime = model.groupBeginTime;
    [QRSingleton sharedQRSingleton].groupEndTime = model.groupEndTime;
    [self.navigationController pushViewController:ggvc animated:YES];
}

#pragma mark -- 长按进入删除模式
-(void)gestureLongPress:(UIGestureRecognizer *)longPress
{
    CGPoint tmPointTouch = [longPress locationInView:groupTabelView];
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [self checkPower:tmPointTouch];
    }
}

#pragma mark ---- 删除时查看操作人的角色（超级管理员才可以删除）
-(void)checkPower:(CGPoint)touchPoint
{
    [self startWaiting:nil color:nil addToView:self.view];
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    __weak GroupViewController * weakSelf = self;
    power.powerBlock = ^(id data,id error)
    {
        [self stopWaiting];
        if ([data objectForKey:@"data"] != nil) {
            NSArray * CommunityArray = [[data objectForKey:@"data"] objectForKey:@"communities"];
            for (NSDictionary * dict in CommunityArray) {
                if ([_communityId isEqualToString:[dict objectForKey:@"communityid"]]) {
                    if ([[dict objectForKey:@"role"] isEqualToString:@"1"]) {
                        [self touchPoint:touchPoint InController:groupTabelView];
                        return ;
                    }
                }
            }
            [PromptInfoView showMessage:NSLocalizedString(@"noPowerDeleteGroup", nil) superView:weakSelf.view];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
    };
}

#pragma mark -- 搜索出来的数据删除
-(void)gesturePress:(UIGestureRecognizer *)press
{
    CGPoint tmPointTouch = [press locationInView:groupDisplayController.searchResultsTableView];
    if (press.state == UIGestureRecognizerStateBegan) {
         [self touchPoint:tmPointTouch InController:groupDisplayController.searchResultsTableView];
    }
}

#pragma mark -- 长按触发删除
-(void)touchPoint:(CGPoint)point InController:(UITableView *)tableView
{
    NSIndexPath * NowPressIndexPath = [tableView indexPathForRowAtPoint:point];
    for (NSIndexPath * deleteIndexPath in deleteCellArray) {
        if (NowPressIndexPath.row == deleteIndexPath.row && NowPressIndexPath.section == deleteIndexPath.section) {
            UITableViewCell * cell = [tableView cellForRowAtIndexPath:NowPressIndexPath];
            [cell mdDeflateAnimatedToPoint:CGPointMake(point.x, point.y - cell.frame.origin.y) backgroundColor:[UIColor whiteColor] duration:0.5 completion:nil];
            [deleteCellArray removeObject:NowPressIndexPath];
            [self showDeleteView];
            return;
        }
    }
    if (NowPressIndexPath == nil) {
        return;
    }
    GroupTableViewCell * cell = (GroupTableViewCell *)[tableView cellForRowAtIndexPath:NowPressIndexPath];
    [cell mdInflateAnimatedFromPoint:CGPointMake(point.x, point.y - cell.frame.origin.y) backgroundColor: RGBA(225, 225, 225, 1) duration:0.5 completion:nil];
    [deleteCellArray addObject:NowPressIndexPath];
    [self showDeleteView];
}

-(void)showDeleteView
{
    deleteView.hidden = NO;
    [self.navigationController.navigationBar addSubview:deleteView];//防止添加组后再删除出现两个返回箭头
    titleView.hidden = YES;
    NSString * locaString = NSLocalizedString(@"havedChoose", nil);
    deleteCountLabel.text = [NSString stringWithFormat:@"%@%lu%@",locaString,(unsigned long)deleteCellArray.count,NSLocalizedString(@"groupCount", nil)];
}


#pragma mark -- 按照拼音排序
-(NSMutableArray*)getChinesArray:(NSArray*)arrToSort
{
    //创建一个临时的变动数组
    int count = (int)arrToSort.count;
    for(int i =0; i < count; i++)
    {
        //创建一个临时的数据模型对象
        ChineseString *chineseString=[[ChineseString alloc]init];
        //给模型赋值
        GroupModel * model = [arrToSort objectAtIndex:i];
        NSString *pinYinResult = [NSString string];
        chineseString.string = model.groupName;
        if(chineseString.string==nil)
        {
            chineseString.string=@"";
        }
        if(![chineseString.string isEqualToString:@""])
        {
            //join(链接) the pinYin (letter字母) 链接到首字母
            char FirstHeader = pinyinFirstLetter([chineseString.string characterAtIndex:0]);
            if ((FirstHeader < 91 && FirstHeader > 64)||(FirstHeader < 123 && FirstHeader > 96)) {
                pinYinResult = [pinYinResult stringByAppendingString:[[NSString stringWithFormat:@"%c",FirstHeader]uppercaseString]];
            }else {
                pinYinResult = @"}";
            }
        }
        model.groupHeaderWord = pinYinResult;
        
    }
    
    NSMutableArray * array = [NSMutableArray arrayWithArray:[arrToSort sortedArrayUsingComparator:^NSComparisonResult(GroupModel * model1, GroupModel * model2) {
        return [model1.groupHeaderWord compare:model2.groupHeaderWord];
    }]];
    return array;
}


-(void)BackClick
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
